export const db = new Dexie('PGPrompterDB');

// Declare tables, IDs and indexes


db.version(1).stores({
	prompts: '++id, name, content, vars, *tags',
});


db.prompts.count()


export async function exportData() {
	console.log('exportData...')

	let content = ''

	const pts = await db.prompts.toArray()
	let pts_str = JSON.stringify(pts);
	content += '\nlet json_prompts = ' + pts_str


	content += '\nconst db_json = {json_prompts: json_prompts}'
	content += '\nexport default db_json'

	return content
}

export const doExportData = async () => {
    const content = await exportData()

    var blob = new Blob([content], {type: "application/json"});
    var url = URL.createObjectURL(blob);
    var link = document.createElement('a');
    link.href = url;
    link.download = 'db.js'; // 指定下载文件的名称

    document.body.appendChild(link);
    link.click();    
  }

export const doImportData = async (db_json) =>{
    // print('importData ', db)

    const json = db_json
    for (let key in json) {
      if (json.hasOwnProperty(key)) {
        const tableName = key.replace('json_', '')
        console.log(`${key}  ${tableName}  : ` + json[key]);

        if (db._storeNames.includes(tableName)) {
          json[key].forEach(it=>{
            print('record', it)
            db.table(tableName).put(it)
          })

        } else {
            console.log(`Table ${tableName} does not exist.`);
        }
      }
    }
}